package tables

import (
	"app/models"
	"fmt"
	"strconv"

	"github.com/GoAdminGroup/go-admin/context"
	"github.com/GoAdminGroup/go-admin/modules/db"
	"github.com/GoAdminGroup/go-admin/plugins/admin/modules/table"
	"github.com/GoAdminGroup/go-admin/template/types"
	"github.com/GoAdminGroup/go-admin/template/types/form"
)

type GreenhouseAllocation struct {
	ID             string
	OrdersName     string
	GreenhouseName string
	// 分配数量
	Quantity int
	// 已分配种子数量
	Allocated int
}

func getGreenhouseAllocationNameById(id string) string {
	var greenhouse GreenhouseAllocation
	err := models.Orm.Table("greenhouse_allocation_record").Select("orders.name as orders_name, greenhouse.name as greenhouse_name, greenhouse_allocation_record.quantity, greenhouse_allocation_record.allocated").
		Joins("left join greenhouse on greenhouse_allocation_record.greenhouse_id = greenhouse.id").
		Joins("left join orders on greenhouse_allocation_record.order_id = orders.id").
		Where("greenhouse_allocation_record.id = ?", id).
		Scan(&greenhouse).Error
	if err != nil {
		fmt.Printf("getGreenhouseAllocationNameById error: %s\n", err.Error())
		return ""
	}
	still := strconv.Itoa(greenhouse.Quantity - greenhouse.Allocated)
	return greenhouse.OrdersName + "-" + greenhouse.GreenhouseName + "(剩余: " + still + " 未分苗床)"
}

func getGreenhouseAllocationOptions() types.FieldOptions {
	var options types.FieldOptions
	var greenhouses []GreenhouseAllocation
	models.Orm.Table("greenhouse_allocation_record").Select("greenhouse_allocation_record.id as id, orders.name as orders_name, greenhouse.name as greenhouse_name, greenhouse_allocation_record.quantity, greenhouse_allocation_record.allocated").
		Joins("left join greenhouse on greenhouse_allocation_record.greenhouse_id = greenhouse.id").
		Joins("left join orders on greenhouse_allocation_record.order_id = orders.id").
		Find(&greenhouses)
	for _, greenhouse := range greenhouses {
		still := strconv.Itoa(greenhouse.Quantity - greenhouse.Allocated)
		options = append(options, types.FieldOption{
			Text:  greenhouse.OrdersName + "-" + greenhouse.GreenhouseName + "(剩余: " + still + " 未分苗床)",
			Value: greenhouse.ID,
		})
	}
	return options
}

func getSeedbedOptions() types.FieldOptions {
	var options types.FieldOptions
	var seedbeds []models.SeedbedDetail
	models.Orm.Table("seedbed").
		Select("seedbed.*, greenhouse.name as greenhouse_name").
		Joins("left join greenhouse on seedbed.greenhouse_id = greenhouse.id").
		Where("seedbed.id > ?", 0).
		Where("seedbed.is_active = ?", 1).
		Find(&seedbeds)
	seedbedMap := make(map[string]map[string][]models.SeedbedDetail)
	for _, seedbed := range seedbeds {
		if _, ok := seedbedMap[seedbed.GreenhouseName]; !ok {
			seedbedMap[seedbed.GreenhouseName] = make(map[string][]models.SeedbedDetail)
		}
		if _, ok := seedbedMap[seedbed.GreenhouseName][seedbed.Area]; !ok {
			seedbedMap[seedbed.GreenhouseName][seedbed.Area] = make([]models.SeedbedDetail, 0)
		}
		seedbedMap[seedbed.GreenhouseName][seedbed.Area] = append(seedbedMap[seedbed.GreenhouseName][seedbed.Area], seedbed)
	}
	for greenhouseName, seedArea := range seedbedMap {
		for area, seeds := range seedArea {
			prefix := greenhouseName + "-" + area
			for _, seedbed := range seeds {
				name := prefix + ": " + seedbed.Name
				options = append(options, types.FieldOption{
					Text:  name,
					Value: strconv.Itoa(seedbed.ID),
				})
			}
		}
	}
	return options
}

func getSeedbedOptionByID(id string) string {
	var seedbed models.SeedbedDetail
	err := models.Orm.Table("seedbed").Joins("left join greenhouse on seedbed.greenhouse_id = greenhouse.id").Where("seedbed.id = ?", id).
		Scan(&seedbed).Error
	if err != nil {
		fmt.Printf("getSeedbedOptionByID error: %s\n", err.Error())
		return ""
	}
	return seedbed.Name + "( 区域:" + seedbed.Area + ")"
}

func GetSeedbedAllocationRecordTable(ctx *context.Context) table.Table {

	seedbedAllocationRecord := table.NewDefaultTable(table.DefaultConfigWithDriver("mysql"))

	info := seedbedAllocationRecord.GetInfo()
	info.SetFilterFormLayout(form.LayoutTwoCol)
	info.AddField("Id", "id", db.Int).
		FieldFilterable().
		FieldSortable()
	info.AddField("订单", "name", db.Varchar).
		FieldJoin(types.Join{
			Table:     "orders",
			JoinField: "id",
			Field:     "order_id",
		}).FieldFilterable(types.FilterType{FormType: form.SelectSingle}).
		FieldFilterOptionsFromTable("orders", "name", "name", func(model *db.SQL) *db.SQL {
			return model.Where("id", ">", 0)
		}).
		FieldSortable()
	info.AddField("大棚", "name", db.Varchar).
		FieldJoin(types.Join{
			Table:     "greenhouse",
			JoinField: "id",
			Field:     "greenhouse_id",
		}).
		FieldFilterable(types.FilterType{FormType: form.SelectSingle}).
		FieldFilterOptionsFromTable("greenhouse", "name", "name", func(model *db.SQL) *db.SQL {
			return model.Where("id", ">", 0).Where("is_active", "=", 1)
		}).
		FieldDisplay(func(value types.FieldModel) interface{} {
			return value.Value
		}).
		FieldSortable()
	info.AddField("大棚分配记录", "greenhouse_allocation_id", db.Int).
		FieldFilterable(types.FilterType{FormType: form.SelectSingle}).
		FieldFilterOptions(getGreenhouseAllocationOptions()).
		FieldDisplay(func(value types.FieldModel) interface{} {
			return getGreenhouseAllocationNameById(strconv.FormatInt(value.Row["greenhouse_allocation_id"].(int64), 10))
		}).
		FieldEditAble()
	info.AddField("苗床", "seedbed_id", db.Int).
		FieldFilterable(types.FilterType{FormType: form.SelectSingle}).
		FieldFilterOptions(getSeedbedOptions()).
		FieldDisplay(func(value types.FieldModel) interface{} {
			fmt.Println(value.Row)
			return getSeedbedOptionByID(strconv.FormatInt(value.Row["seedbed_id"].(int64), 10))
		}).
		FieldEditAble()
	info.AddField("分配数量", "quantity", db.Int).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("分配盘数", "tray_number", db.Int).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("每盘数量", "unit_number", db.Int).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("备注", "remark", db.Varchar).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("创建时间", "created_at", db.Timestamp).
		FieldSortable()
	info.AddField("更新时间", "updated_at", db.Timestamp).
		FieldSortable()

	info.SetTable("seedbed_allocation_record").SetTitle("苗床分配记录").SetDescription("SeedbedAllocationRecord")

	formList := seedbedAllocationRecord.GetForm()
	formList.AddField("Id", "id", db.Int, form.Default).
		FieldDisableWhenCreate().
		FieldDisableWhenUpdate()
	formList.AddField("订单", "order_id", db.Int, form.SelectSingle).FieldOptionsFromTable("orders", "name", "id", func(model *db.SQL) *db.SQL {
		return model.Where("id", ">", 0)
	}).FieldHelpMsg("请选择订单")
	formList.AddField("大棚", "greenhouse_id", db.Int, form.SelectSingle).FieldOptionsFromTable("greenhouse", "name", "id", func(model *db.SQL) *db.SQL {
		return model.Where("id", ">", 0).Where("is_active", "=", 1)
	}).FieldHelpMsg("请选择大棚")
	formList.AddField("大棚分配记录", "greenhouse_allocation_id", db.Int, form.SelectSingle).FieldOptions(getGreenhouseAllocationOptions())
	formList.AddField("苗床", "seedbed_id", db.Int, form.SelectSingle).FieldOptions(getSeedbedOptions()).FieldHelpMsg("请选择苗床")
	formList.AddField("分配数量", "quantity", db.Int, form.Number)
	formList.AddField("分配盘数", "tray_number", db.Int, form.Number)
	formList.AddField("每盘数量", "unit_number", db.Int, form.Number)
	formList.AddField("备注", "remark", db.Varchar, form.Text)
	formList.AddField("创建时间", "created_at", db.Timestamp, form.Datetime).
		FieldDisableWhenUpdate().
		FieldHide().FieldNowWhenInsert()
	formList.AddField("修改时间", "updated_at", db.Timestamp, form.Datetime).
		FieldDisableWhenCreate().
		FieldHide().FieldNowWhenUpdate()

	formList.SetTable("seedbed_allocation_record").SetTitle("苗床分配记录").SetDescription("SeedbedAllocationRecord")

	return seedbedAllocationRecord
}
